package consul

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"shyxy-net/common/schema"
)

type Client struct {
	Address string
	client  *http.Client
}

func NewConsulClient(address string) *Client {
	return &Client{
		Address: address,
		client:  http.DefaultClient,
	}
}

func (c *Client) RegisterService(serviceConfig *ServiceConfig) error {
	service := map[string]interface{}{
		"ID":      serviceConfig.ID,
		"Name":    serviceConfig.Name,
		"Port":    serviceConfig.Port,
		"Address": serviceConfig.Address,
		"Check": map[string]interface{}{
			"HTTP":     schema.URL(schema.HTTP, serviceConfig.Address, serviceConfig.Port, serviceConfig.CheckPath),
			"Interval": "10s",
			"Timeout":  "5s",
		},
	}
	jsonData, err := json.Marshal(service)
	if err != nil {
		return fmt.Errorf("failed to marshal service data: %w", err)
	}
	url := fmt.Sprintf("%s/v1/agent/service/register", c.Address)
	req, err := http.NewRequest("PUT", url, bytes.NewBuffer(jsonData))
	if err != nil {
		return fmt.Errorf("failed to create register request: %w", err)
	}
	resp, err := c.client.Do(req)
	if err != nil {
		return fmt.Errorf("failed to send register request: %w", err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("consul registration failed with status: %s", resp.Status)
	}
	return nil
}

func (c *Client) DeregisterService(id string) error {
	url := fmt.Sprintf("%s/v1/agent/service/deregister/%s", c.Address, id)
	req, err := http.NewRequest("PUT", url, nil)
	if err != nil {
		return err
	}
	resp, err := c.client.Do(req)
	if err != nil {
		return fmt.Errorf("failed to send deregister request: %w", err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("consul deregistration failed with status: %s", resp.Status)
	}
	return nil
}
